package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.constant.CartConstant;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法(controller的请求方法)之前,判断用户的登录状态(是临时用户还是登录用户)。并封装传递给controller目标请求
 */
// 注意,拦截器需要配合web配置使用
public class CartInterceptor implements HandlerInterceptor {
    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();
    // 会在目标方法(controller的请求方法)执行之前拦截;return true放行这个目标方法;return false 不放行;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (member != null) {
            // 用户登录了
            userInfoTo.setUserId(member.getId());
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null&&cookies.length>0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){// 说明是临时身份,因为京东为游客身份一个key叫user-key
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }
            }
        }
        /**
         * 如果用户登录额
         */
        if (StringUtils.isEmpty(userInfoTo.getUserKey())){
            // 如果临时用户是空的 说明没有临时用户,我们自定义一个临时用户
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行以后,让浏览器保存一个cookie,1个月时间
     *
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        UserInfoTo userInfoTo = threadLocal.get();
        if (!userInfoTo.isTempUser()){// 因为我们用的是boolean,不是包装类,因此是isTempUser,而非getTempUser
            // 不是临时用户信息
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");//作用域调到父域,让他作用域变大
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);// 单位秒,我们给的是一个月过期
            response.addCookie(cookie);
        }

    }
}
